<template>
  <div class="find">
    <van-form @submit="onSubmit">
      <van-field
        v-model="formValue.phone"
        name="手机号"
        label="手机号"
        placeholder="手机号"
        :rules="[{ validator, message: '请填写正确的手机号' }]"
      />
      <van-field
        v-model="formValue.code"
        type="password"
        name="验证码"
        label="验证码"
        placeholder="验证码"
        :rules="[{ required: true, message: '请填写验证码' }]"
      >
        <template #button>
          <van-button
            native-type="button"
            type="primary"
            :disabled="buttonDis"
            @click="sendClick"
          >{{btnText}}</van-button>
        </template>
      </van-field>
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit">提交</van-button>
      </div>
    </van-form>
  </div>
</template>
<script>
import {getCode,login} from '../../api'
export default {
  data() {
    return {
      formValue: {
        phone:"",
        code:""
      },
      btnText: "发送验证码",
      buttonDis: false //禁用与否
    };
  },
  methods: {
    //手机验证
    validator(value) {
      return /^(?:(?:\+|00)86)?1\d{10}$/.test(value);
    },
    onSubmit() {
      login(this.formValue).then((res) => {
        // console.log(res)
          // 获取token
          localStorage.setItem('token', res.data.data.token)
          window.localStorage.setItem("userForm", JSON.stringify(res.data.data));
          console.log(res)
          // 先跳转页面到/home
          this.$router.push('/')
          // 轻提示
          this.$toast.success({ message: res.msg});
      });
    },
    getcode() {
      getCode().then(res => {
        console.log(res);
        // this.$toast({ message: `验证码为${res.data}`, duration: 3000 });
      });
    },
    sendClick() {
      if (!this.formValue.phone) {
        //轻提示
        this.$toast("请输入手机号");
        return;
      } else if (!this.validator(this.formValue.phone)) {
        //轻提示
        this.$toast("请输入正确手机号");
      }
      if (!this.formValue.phone) {
        this.$toast("请输入手机号");
        return;
      }

      this.getcode();

      this.buttonDis = true;
      let timeOut = 30; //倒计时
      let timer = null;
      timer = setInterval(() => {
        //逐次减一
        timeOut = timeOut - 1;
        this.btnText = `${timeOut}s后重试`;
        if (timeOut <= 0) {
          clearInterval(timer);
          this.buttonDis = false;
          this.btnText = "发送验证码";
        }
      }, 1000);
    }
  }
};
</script>

<style>
.find {
  width: 100%;
  height: 100%;
  background: rgb(230, 228, 228);
}
.find-header {
  width: 100%;
  height: 20%;
  line-height: 60px;
  background: rgb(184, 181, 181);
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}
.find-main {
  width: 100%;
  height: 70%;
  background: #fff;
}
.find-main > li {
  width: 100%;
  height: 10%;
  line-height: 50px;
  border-bottom: 1px solid #ccc;
}
</style>